package com.xiaoq.ar.repository.impl;

import com.xiaoq.ar.entity.ARActivityEntity;
import com.xiaoq.ar.repository.ARActivityRepository;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenjh on 2018/3/5.
 */
@Repository
public class ARActivityRepositoryImpl implements ARActivityRepository {

    @Autowired
    private Datastore dataStore;

    private Logger logger = LoggerFactory.getLogger(ARActivityRepositoryImpl.class);

    @Override
    public boolean save(ARActivityEntity entity) {
        if(entity==null || StringUtils.isBlank(entity.getId())){
            return false;
        }
        dataStore.save(entity);
        return true;
    }

    @Override
    public ARActivityEntity getByPrimaryId(String id) {
        if(StringUtils.isBlank(id)){
            return null;
        }
        Query<ARActivityEntity> query = dataStore.createQuery(ARActivityEntity.class)
                .filter("_id", id);

        return query.get();
    }

    @Override
    public List<ARActivityEntity> getByProviderId(String providerId) {
        if(StringUtils.isBlank(providerId)){
            return new ArrayList<>();
        }
        Query<ARActivityEntity> query = dataStore.createQuery(ARActivityEntity.class)
                .filter("providerId", providerId);

        return query.asList();
    }

    @Override
    public ARActivityEntity getLatestByProviderId(String providerId) {
        if(StringUtils.isBlank(providerId)){
            return null;
        }
        Query<ARActivityEntity> query = dataStore.createQuery(ARActivityEntity.class)
                .filter("providerId", providerId)
                .order("- createdAt");

        return query.get();
    }
}
